import { getToken } from "@/utils/auth";

// 登录页面
const loginPage = "/pages/login";
// 404页面
const notFoundPage = "/pages/common/404/index";

// 页面白名单
const whiteList = [
    "/pages/login",
    "/pages/register",
    "/pages/common/webview/index",
    "/pages/common/404/index",
];

// 被拦截的API路径列表
const blockedApiPaths = ["/api/actuator"];

// 检查地址白名单
function checkWhite(url) {
    const path = url.split("?")[0];
    return whiteList.indexOf(path) !== -1;
}

// 检查是否为被拦截的API路径
function checkBlockedApi(url) {
    const path = url.split("?")[0];
    return blockedApiPaths.some((blockedPath) => path.includes(blockedPath));
}

// 页面跳转验证拦截器
let list = ["navigateTo", "redirectTo", "reLaunch", "switchTab"];
list.forEach((item) => {
    uni.addInterceptor(item, {
        invoke(to) {
            // 检查是否为被拦截的API路径
            if (checkBlockedApi(to.url)) {
                console.log("拦截API路径:", to.url);
                uni.reLaunch({ url: notFoundPage });
                return false;
            }

            if (getToken()) {
                if (to.url === loginPage) {
                    console.log("是不是这里走了重定向");
                    uni.reLaunch({ url: "/" });
                }
                return true;
            } else {
                console.log("看看这里", to.url);
                if (checkWhite(to.url)) {
                    return true;
                }
                console.log("测试是否这里跳转登录页", loginPage);
                uni.reLaunch({ url: loginPage });
                return false;
            }
        },
        fail(err) {
            console.log(err);
        },
    });
});
